package com.ailesson.user.service.impl;

import com.ailesson.common.except.GlobalErrorCodeConstants;
import com.ailesson.common.except.ServiceException;
import com.ailesson.user.dto.UserInfoSimpleDto;
import com.ailesson.user.entity.UserInfoEntity;
import com.ailesson.user.mapper.UserInfoMapper;
import com.ailesson.user.model.reply.UserInfoReply;
import com.ailesson.user.service.UserInfoService;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;

import com.ailesson.user.model.req.UserInfoQueryReq;
import com.ailesson.user.model.req.UserInfoReq;
import com.ailesson.common.reply.PageResult;
import cn.hutool.core.collection.CollectionUtil;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfoEntity> implements UserInfoService {

    @Override
    public PageResult queryPage(UserInfoQueryReq params) {
       Page pageTmp = Page.of(params.getPageNo(),params.getPageSize());
       IPage<UserInfoEntity> page = this.page(
               pageTmp,
               new LambdaQueryWrapper<>()
       );
       List<UserInfoReply> replyList = Collections.EMPTY_LIST;
       if (CollectionUtil.isNotEmpty(page.getRecords())){
           replyList = page.getRecords().stream().map(x -> {
               UserInfoReply reply = new UserInfoReply();
               BeanUtils.copyProperties(x, reply);
               return reply;
           }).collect(Collectors.toList());
       }
       return new PageResult<>(replyList,page.getTotal());
    }

    @Override
    public UserInfoReply info(Long id) {
        UserInfoEntity entity = this.getById(id);
        if (entity != null){
            UserInfoReply reply = new UserInfoReply();
            BeanUtils.copyProperties(entity, reply);
            return reply;
        }
        return null;
    }

    @Transactional(
            rollbackFor = {Exception.class}
    )
    @Override
    public void update(UserInfoReq userInfo) {
        if (userInfo.getId() == null || userInfo.getId() <= 0){
            throw new ServiceException(GlobalErrorCodeConstants.ID_EMPTY_ERROR);
        }
        UserInfoEntity entity = this.getById(userInfo.getId());
        if (entity == null){
            throw new ServiceException(GlobalErrorCodeConstants.NOT_EXISTS_ERROR);
        }
        BeanUtils.copyProperties(userInfo, entity);
        this.updateById(entity);
    }

    @Transactional(
            rollbackFor = {Exception.class}
    )
    @Override
    public void add(UserInfoReq userInfo) {
        userInfo.setId(null);
        UserInfoEntity entity = new UserInfoEntity();
        BeanUtils.copyProperties(userInfo, entity);
        this.save(entity);
    }

    @Override
    public List<UserInfoSimpleDto> batchSimple(List<Long> ids) {
        List<UserInfoEntity> list = this.list(new LambdaQueryWrapper<UserInfoEntity>()
                .select(UserInfoEntity::getId, UserInfoEntity::getName, UserInfoEntity::getNickName,UserInfoEntity::getPhone)
                .in(UserInfoEntity::getId, ids));
        return list.stream().map(x -> {
            UserInfoSimpleDto simpleDto = new UserInfoSimpleDto();
            BeanUtils.copyProperties(x,simpleDto);
            return simpleDto;
        }).collect(Collectors.toList());
    }

    @Override
    public UserInfoReply getOrSaveUserInfoOpenId(WxOAuth2UserInfo wxMpUser, String openId) {
        UserInfoEntity userInfo = this.getOne(new LambdaQueryWrapper<UserInfoEntity>().eq(UserInfoEntity::getOpenId, openId).last(" limit 1 "));
        if (userInfo == null){
            userInfo = new UserInfoEntity();
            userInfo.setOpenId(openId);
            userInfo.setNickName(wxMpUser.getNickname());
            userInfo.setAvatar(wxMpUser.getHeadImgUrl());
            userInfo.setSex(wxMpUser.getSex());
            userInfo.setProvince(wxMpUser.getProvince());
            userInfo.setUnionId(wxMpUser.getUnionId());
            this.save(userInfo);
        }
        UserInfoReply userInfoReply = new UserInfoReply();
        BeanUtils.copyProperties(userInfo,userInfoReply);
        return userInfoReply;
    }
}